package ua.maxicash.util;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class LoggingInterceptor {

    private static final Logger logger = Logger.getLogger(LoggingInterceptor.class);

    @Pointcut("execution(* ua.maxicash..*.*(..))")
    public void log() {
    }

    @Around("log()")
    public Object logAll(ProceedingJoinPoint joinPoint) throws Throwable {
        Object retVal = null;
        StringBuilder logMessageStringBuffer = new StringBuilder();
        logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName());
        logMessageStringBuffer.append(".");
        logMessageStringBuffer.append(joinPoint.getSignature().getName());
        logMessageStringBuffer.append("(");
        logMessageStringBuffer.append(Arrays.deepToString(joinPoint.getArgs()));
        logMessageStringBuffer.append(")");

        //try {
            retVal = joinPoint.proceed();
            logger.info(logMessageStringBuffer.toString());
            return retVal;
//        } catch (Throwable throwable) {
//            logger.error(logMessageStringBuffer.toString() + "\n"
//                    + throwable.getMessage() +"\n"
//                    + Arrays.deepToString(throwable.getStackTrace()));
//            return retVal;
            //logger.error(throwable);
//        }

    }

}
